<template>
  <el-dialog title="新增" :close-on-click-modal="false" :visible.sync="visible">
    <el-steps :active="active" finish-status="success">
      <el-step title="选择店铺"></el-step>
      <el-step title="选择酒店"></el-step>
    </el-steps>
    <!--选择店铺-->
    <el-form
      :model="dataForm"
      v-if="active === 0"
      inline
      ref="dataForm"
      label-width="80px"
      style="width: 100%"
    >
      <el-form-item prop="pfId" label label-width="0px">
        <el-select
          v-model="dataForm.pfId"
          @change="pfChange"
          placeholder="请选择销售平台"
          style="width: 100%"
        >
          <el-option
            v-for="item in pfs"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="storId" label label-width="0px">
        <el-select v-model="dataForm.storId" placeholder="请选择店铺" style="width: 100%">
          <el-option
            v-for="item in stores"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!--选择酒店-->
    <template v-if="active === 1">
      <el-tabs v-model="dataForm.authType" type="border-card">
        <el-tab-pane name="1" label="批量上架">
          <el-radio v-model="dataForm.authAll" label="1">上架所有酒店</el-radio>
          <el-radio v-model="dataForm.authAll" label="0">上架指定条件酒店</el-radio>
          <el-form :inline="true" :model="dfHotel" v-if="dataForm.authAll === '0'">
            <el-form-item>
              <el-select
                v-model="dfHotel.province"
                clearable
                @change="proChange"
                placeholder="请选择省份"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="dfHotel.city"
                clearable
                @change="cityChange"
                placeholder="请选择城市"
              >
                <el-option
                  v-for="item in citys"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="dfHotel.county" clearable placeholder="请选择区域">
                <el-option
                  v-for="item in countys"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="dfHotel.brand"
                multiple
                clearable
                placeholder="请选择品牌"
              >
                <el-option
                  v-for="item in brands"
                  :key="item.id"
                  :label="item.bname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="2" label="上架指定酒店">
          <el-row style="margin-bottom: 10px">
            <el-form :inline="true" :model="dataForm">
              <el-form-item>
                <el-input v-model="dataForm.hotelName" placeholder="酒店名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="dataForm.province"
                  clearable
                  @change="proChange"
                  placeholder="请选择省份"
                >
                  <el-option
                    v-for="item in provinces"
                    :key="item.cityCode"
                    :label="item.cityNameZh"
                    :value="item.cityCode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="dataForm.city"
                  clearable
                  @change="proChange"
                  placeholder="请选择城市"
                >
                  <el-option
                    v-for="item in citys"
                    :key="item.cityCode"
                    :label="item.cityNameZh"
                    :value="item.cityCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <el-col :span="7" style="margin-left: 22px">
              <el-button type="primary" @click="queryByName">查询</el-button>
              <el-button
                type="primary"
                @click="select"
                :disabled="dataListSelections.length <= 0"
                >添加</el-button
              >
            </el-col>
          </el-row>
          <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%"
          >
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50"
            ></el-table-column>
            <el-table-column
              prop="hotelName"
              header-align="center"
              align="center"
              label="酒店名称"
            ></el-table-column>
            <el-table-column
              prop="address"
              header-align="center"
              align="center"
              label="酒店地址"
            ></el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[5, 10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </el-tab-pane>
        <el-tab-pane name="3" label="EXCEL上架酒店">
          <el-form :inline="true" :model="dataForm">
              <el-upload
                class="upload-demo"
                action=""
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :limit="limitUpload"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                :auto-upload="false"
              >
                <el-button size="small" type="primary">点击导入酒店</el-button>
              </el-upload>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </template>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="prev" v-if="active != 0">上一步</el-button>
      <el-button type="primary" @click="next" v-if="active != 2">下一步</el-button>
      <el-button 
        type="primary"
        :disabled="isExcu"
        @click="dataFormSubmit"
        v-if="active === 2"
        >提交</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
export default {
  data() {
    return {
      limitUpload: 1,
      fileTemp: null,
      file: null,
      da: [],
      dalen: 0,
      isExcu: false,
      visible: false,
      active: 0,
      dfHotel: {
        province: null,
        city: null,
        county: null,
        brand: null,
        hotelName: null,
      },
      pfs: [],
      stores: [],
      tier: 1,
      parentId: -1,
      provinces: [],
      citys: [],
      countys: [],
      brands: [],
      dataForm: {
        authType: "1",
        authAll: "1",
        dtId: "",
        pfId: null,
        storId: null,
        hotelName: "",
        hotelIds: [],
        city: null,
        county: null,
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 5,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
    };
  },
  methods: {
    //上传文件时处理方法
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      this.importfxx(this.fileTemp);

    },
    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            arr.push(v["酒店id"]);
          });
          console.info(arr);
          _this.dataForm.hotelIds = arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    // 导出excel
    // export2Excel() {
    //   require.ensure([], () => {
    //     let { export_json_to_excel } = require("../../../utils/Export2Excel");
    //     // 表头
    //     let tHeader = ["酒店id", "酒店名称"];
    //     //表头对应字段名，要和下面数据key对应
    //     let filterVal = ["id", "hotelName"];
    //     // 数据来源
    //     let list = this.dataList;

    //     let data = this.formatJson(filterVal, list); //数据格式化
    //     var index1 = "酒店列表"; //导出时文件名
    //     export_json_to_excel(tHeader, data, index1); //导出文件
    //   });
    // },
    // 数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 选择销售平台获取销售平台下的店铺
    pfChange(value) {
      this.dataForm.storId = null;
      this.$http({
        url: this.$http.adornUrl("/op/dtuphtl/store"),
        method: "get",
        params: this.$http.adornParams({
          dtId: this.dataForm.dtId,
          pfId: this.dataForm.pfId,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.stores = data.list;
        } else {
          this.stores = [];
        }
      });
    },
    prev() {
      this.active--;
    },
    next() {
      // 第一步选择店铺
      if (this.active === 0 && this.dataForm.storId === null) {
        this.$alert("选择店铺", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
        return;
      }
      // 第二步，按照区域授权
      if (
        this.active === 1 &&
        this.dataForm.authType === "1" &&
        this.dataForm.authAll === "0"
      ) {
        if (
          this.dfHotel.province === null &&
          this.dfHotel.city === null &&
          this.dfHotel.county === null &&
          (this.dfHotel.brand === null || this.dfHotel.brand.length <= 0)
        ) {
          this.$alert("请选择授权的区域或品牌", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return;
        }
      }
      // 第二步，授权指定酒店
      if (this.active === 1 && this.dataForm.authType === "2") {
        if (this.dataForm.hotelIds.length <= 0 && this.dataListSelections.length <= 0) {
          this.$alert("请选择授权的酒店", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return;
        }
      }
      // 第三步excel不能为空
      if(this.active === 1 && this.dataForm.authType === "3") {
        if(this.dataForm.hotelIds.length <= 0 || this.dataForm.hotelIds.length > 2000) {
          this.$alert("excel表数据应为0-2000条", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return;
        }
      }
      this.active++;
    },
    // 获取区域查询条件
    getQuryCitys() {
      this.$http({
        url: this.$http.adornUrl("/op/dtuphtl/citys"),
        method: "post",
        params: this.$http.adornParams({
          tier: this.tier,
          parentId: this.parentId,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          switch (this.tier) {
            case 1:
              this.provinces = data.list;
              break;
            case 2:
              this.citys = data.list;
              break;
            case 3:
              this.countys = data.list;
              break;
          }
        }
      });
    },
    // 选择省份
    proChange(value) {
      this.parentId = value;
      this.tier = 2;
      this.getQuryCitys();
    },
    // 选择城市
    cityChange(value) {
      this.parentId = value;
      this.tier = 3;
      this.getQuryCitys();
    },
    // 获取指定的酒店（按酒店名称）
    getDataList() {
      this.dataListSelections = [];
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/op/dtuphtl/htls"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          dtId: this.dataForm.dtId,
          pf: this.dataForm.pfId,
          storId: this.dataForm.storId,
          name: this.dataForm.hotelName,
          city: this.dataForm.city,
          county: this.dataForm.county,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // getDataListAll() {
    //   this.dataListLoading = true;
    //   this.export2Excel();
    //   this.dataListLoading = false;
      // this.$http({
      //   url: this.$http.adornUrl("/op/dtuphtl/htlsall"),
      //   method: "get",
      //   params: this.$http.adornParams({
      //     dtId: this.dataForm.dtId,
      //     pf: this.dataForm.pfId,
      //     storId: this.dataForm.storId,
      //     name: this.dataForm.hotelName,
      //     city: this.dataForm.city,
      //     county: this.dataForm.county,
      //   }),
      // }).then(({ data }) => {
      //   if (data && data.code === 0) {
      //     this.dataList = data.list;
      //     this.export2Excel();
      //   } else {
      //     this.dataList = [];
      //     this.totalPage = 0;
      //   }
      //   this.dataListLoading = false;
      // });
    // },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    queryByName() {
      this.pageIndex = 1;
      this.getDataList();
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    select() {
      if (this.dataListSelections.length <= 0) {
        return;
      }
      let ids = this.dataListSelections.map((item) => {
        return item.id;
      });
      console.log("this.dataForm.hotelIds", this.dataForm.hotelIds);
      // 把选择的酒店添加到酒店列表
      this.dataForm.hotelIds = this.dataForm.hotelIds.concat(ids);
      console.log("ids", ids);
      // 去重
      this.dataForm.hotelIds = this.dataForm.hotelIds.filter((item, index) => {
        return this.dataForm.hotelIds.indexOf(item) === index;
      });
      this.dataListSelections = [];
    },
    init(dtId, pfs, provinces, brands) {
      this.dataForm.dtId = dtId;
      this.pfs = pfs;
      this.provinces = provinces;
      this.brands = brands;
      this.visible = true;
      this.active = 0;
      this.dataListSelections = [];
      this.dataForm.hotelIds = [];
    },
    // 表单提交
    dataFormSubmit() {
      this.isExcu = true;
      this.select();

      this.$http({
        url: this.$http.adornUrl("/op/dtuphtl/save"),
        method: "post",
        data: this.$http.adornData({
          dtId: this.dataForm.dtId,
          storId: this.dataForm.storId,
          authType: this.dataForm.authType,
          authAll: this.dataForm.authAll,
          // 'province': this.dataForm.province,
          city: this.dataForm.city,
          county: this.dataForm.county,
          brand: this.dfHotel.brand,
          hotelIds: this.dataForm.hotelIds,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: data.msg,
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.isExcu = false;
              this.$emit("refreshDataList");
            },
          });
        } else {
          this.$message.error(data.msg);
          this.isExcu = false;
        }
        this.dataListSelections = [];
        this.dataForm.hotelIds = [];
      });
    },
  },
};
</script>
